package com.zhhs.galaxyott.utils;

import java.util.Date;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.zhhs.galaxyott.Constant;
import com.zhhs.galaxyott.http.api.RequestMaker;
import com.zhhs.galaxyott.httpVolley.base.ResponseListener;
import com.zhhs.galaxyott.httpVolley.response.UniversalResponse;
import com.zhhs.galaxyott.httpVolley.response.getPayPlatformURLResponse;
import com.zhhs.galaxyott.sharepreference.SharedPrefHelper;
import com.zhhs.galaxyott.utils.OrderTipDialog.DialogCallback;

public class PurchaseOrPayUtils {

    private static OrderTipDialog dialog;

    public static void getPayPlatformUrlAndJump(final Context mContext, Double price) {

        final SharedPrefHelper sp = SharedPrefHelper.getInstance(mContext);

        String orderId = "SFYX" + new Date().getTime() + ((int) ((Math.random() * 9 + 1) * 100000));
        Double payAmount = price;
        String targetId = sp.getStbid();
        String cardNo = sp.getsmartcard();

        String returnUrl = "myccntvhall://platformapi/return";
        String homeUrl = "myccntvhall://platformapi/home";

        RequestMaker.getPayPlatformURL(targetId, cardNo, payAmount, returnUrl, homeUrl,
                new ResponseListener<getPayPlatformURLResponse>() {

                    @Override
                    public void onResponse(getPayPlatformURLResponse result) {
                        Logs.logD("DEBUG_DT", "THIS IS getPayPlatformURL-->" + result.errCode + result.getPayurl());
                        if (result != null && result.errCode == 0) {

                            String playUrl = result.getPayurl();

                            payJump(playUrl, sp, mContext);
                        } else {
                            Toast.makeText(mContext, "请求失败，请重试", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(VolleyError error) {
                        Logs.logD("DEBUG_DT", "THIS IS getPayPlatformURL-->ERR");
                        Toast.makeText(mContext, "请求错误", Toast.LENGTH_SHORT).show();
                    }
                });

    }

    private static void payJump(String playUrl, SharedPrefHelper sp, Context mContext) {
        ComponentName component = new ComponentName("com.crunii.ccn.tvhall",
                "com.crunii.ccn.tvhall.activity.PayActivity");
        Intent intent = new Intent();
        intent.setComponent(component);

        intent.putExtra("payurl", playUrl);

        mContext.startActivity(intent);
        ((Activity) mContext).finish();
    }

    // 此方法不允许在主线程中处理
    public static void getComboValid(final Context mContext, final String comboId, final Double price) {

        final SharedPrefHelper sp = SharedPrefHelper.getInstance(mContext);
        // 命名空间
        String nameSpace = Constant.nameSpace;
        // 调用的方法名称
        String methodName = "intfComboValid";
        // EndPoint
        String endPoint = Constant.endPoint;
        // SOAP Action
        String soapAction = nameSpace + methodName;

        // 指定WebService的命名空间和调用的方法名
        SoapObject rpc = new SoapObject(nameSpace, methodName);
        // rpc.addProperty("Content-Type", "text/xml; charset=utf-8");

        // 设置需调用WebService接口需要传入的参数
        if (!Constant.isProducted) {
            rpc.addProperty("servNo", "9950000002100169");
            rpc.addProperty("comboId", "1155");
            rpc.addProperty("channelCode", "7012");
        } else {
            rpc.addProperty("servNo", sp.getsmartcard());
            rpc.addProperty("comboId", comboId);
            rpc.addProperty("channelCode", "7012");
        }

        // 使用传的参数

        // 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);

        envelope.bodyOut = rpc;
        // 设置是否调用的是dotNet开发的WebService
        // envelope.dotNet = true;
        (new MarshalBase64()).register(envelope);
        // 等价于envelope.bodyOut = rpc;
        // envelope.setOutputSoapObject(rpc);

        HttpTransportSE transport = new HttpTransportSE(endPoint);
        transport.debug = true;
        try {
            // 调用WebService
            Logs.logD("DEBUG_LC", "THIS IS getComboValid CALL-->:" + nameSpace + "endPoint" + endPoint);
            transport.call(soapAction, envelope);
        } catch (Exception e) {
            PromptsUtils.showToast(((Activity) mContext), "获取数据出错，请稍后再试！", null);
            e.printStackTrace();
        }

        // 获取返回的数据
        SoapObject object;
        try {
            if (envelope.getResponse() != null) {
                object = (SoapObject) envelope.getResponse();
            } else {
                object = (SoapObject) envelope.bodyIn;
            }
            // 获取返回的结果
            if (object == null) {
                PromptsUtils.showToast(((Activity) mContext), "请检查网络！", null);
                return;
            }
            String result = object.getProperty(0).toString();
            final String msg = object.getProperty(1).toString();
            Logs.logD("DEBUG_LC", "THIS IS getComboValid result:" + result);
            if (result.equals("200")) {
                final String intfSeq = object.getProperty(4).toString();
                Logs.logD("DEBUG_LC", "THIS IS getComboValid result:" + intfSeq);
                ((Activity) mContext).runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        dialog = new OrderTipDialog(mContext, "可以办理此套餐业务，确认办理？", new DialogCallback() {
                            @Override
                            public void Confirm() {
                                new Thread(new Runnable() {

                                    @Override
                                    public void run() {
                                        dialog.dismiss();
                                        getComboOrder(mContext, sp, comboId, intfSeq, price);

                                    }
                                }).start();

                            }

                            @Override
                            public void Cancel() {

                            }
                        });
                        dialog.show();
                    }
                });

                // PromptsUtils.showToast(((Activity) mContext), msg, null);
            } else if (result.equals("300")) {
                ((Activity) mContext).runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        dialog = new OrderTipDialog(mContext, "余额不足" + "，点击确认进入支付页面", new DialogCallback() {
                            @Override
                            public void Confirm() {
                                dialog.dismiss();
                                getPayPlatformUrlAndJump(mContext, price);

                            }

                            @Override
                            public void Cancel() {

                            }
                        });
                        dialog.show();

                    }
                });
            } else {

                PromptsUtils.showToast(((Activity) mContext), msg, null);

            }

            Logs.logD("DEBUG_LC", "THIS IS result:" + result + "count:" + object.getPropertyCount());
            Logs.logD("DEBUG_LC", "THIS IS result:1" + object.getProperty(1).toString());
        } catch (SoapFault e) {
            PromptsUtils.showToast(((Activity) mContext), "获取数据出错，请稍后再试！", null);
            e.printStackTrace();
        }

    }

    private static void getComboOrder(Context mContext, SharedPrefHelper sp, String comboId, String intfSeq,
            Double price) {

        // 命名空间
        String nameSpace = Constant.nameSpace;
        // 调用的方法名称
        String methodName = "intfComboOrder";
        // EndPoint 请求URL
        String endPoint = Constant.endPoint;
        // SOAP Action
        String soapAction = nameSpace + methodName;

        // 指定WebService的命名空间和调用的方法名
        SoapObject rpc = new SoapObject(nameSpace, methodName);
        // rpc.addProperty("Content-Type", "text/xml; charset=utf-8");
        // 设置需调用WebService接口需要传入的参数
        if (!Constant.isProducted) {
            rpc.addProperty("servNo", "9950000002100169");
            rpc.addProperty("comboId", "1155");
            rpc.addProperty("channelCode", "7012");
            rpc.addProperty("intfSeq", "SEQ201606211026048365");
        } else {
            rpc.addProperty("servNo", sp.getsmartcard());
            rpc.addProperty("comboId", comboId);
            rpc.addProperty("channelCode", "7012");
            rpc.addProperty("intfSeq", intfSeq);
        }
        Logs.logD("DEBUG_LC", "THIS IS intfSeq:" + intfSeq);
        // 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);

        envelope.bodyOut = rpc;
        // 设置是否调用的是dotNet开发的WebService
        // envelope.dotNet = true;
        (new MarshalBase64()).register(envelope);
        // 等价于envelope.bodyOut = rpc;
        // envelope.setOutputSoapObject(rpc);

        HttpTransportSE transport = new HttpTransportSE(endPoint);
        transport.debug = true;
        try {
            // 调用WebService
            Logs.logD("DEBUG_LC", "THIS IS CALL:");
            transport.call(soapAction, envelope);
        } catch (Exception e) {
            PromptsUtils.showToast(((Activity) mContext), "获取数据出错，请稍后再试！", null);
            e.printStackTrace();
        }

        // 获取返回的数据
        SoapObject object;
        try {
            if (envelope.getResponse() != null) {
                object = (SoapObject) envelope.getResponse();
            } else {
                object = (SoapObject) envelope.bodyIn;
            }
            Log.i("DEBUG_LC", "THIS IS result:0");
            // 获取返回的结果
            String result = object.getProperty(0).toString();
            String msg = object.getProperty(1).toString();
            if (result.equals("200")) {
                // 订购成功修改Vip状态
                sp.setIsVip(true);
                // 反馈订购状态給后台
                addOrderToBackstage(sp, 2, price, 1);
                PromptsUtils.showToast(((Activity) mContext), msg, null);
            } else {
                addOrderToBackstage(sp, 2, price, 2);
                PromptsUtils.showToast(((Activity) mContext), msg, null);
            }

            Logs.logD("DEBUG_LC", "THIS IS result:" + result + "count:" + object.getPropertyCount());
            Logs.logD("DEBUG_LC", "THIS IS result:1" + object.getProperty(1).toString());
        } catch (SoapFault e) {
            PromptsUtils.showToast(((Activity) mContext), "获取数据出错，请稍后再试！", null);
            e.printStackTrace();
        }

    }

    // orderType 订单类型：1单次点播；2包月套餐
    // orderPrice 订单金额(元)
    // orderStatus 订单状态：0订购失败；1订购成功,2取消订购
    // contentId 订购内容ID，如orderType=1传影片ID，如orderType=2传套餐ID
    public static void addOrderToBackstage(final SharedPrefHelper sp, final int orderType, Double orderPrice,
            int orderStatus) {

        RequestMaker.addOrder(sp.getsmartcard(), sp.getStbid(), orderType, orderPrice, orderStatus, Constant.contentId,
                new ResponseListener<UniversalResponse>() {

                    @Override
                    public void onResponse(UniversalResponse result) {
                        Logs.logD("DEBUG_DT", "THIS IS addOrderToBackstage-->param" + sp.getsmartcard() + "orderType"
                                + orderType + "Constant.contentId" + Constant.contentId);
                        Logs.logD("DEBUG_DT",
                                "THIS IS addOrderToBackstage-->result:" + result.msg + "::" + result.getResult());
                    }

                    @Override
                    public void onError(VolleyError error) {
                        Logs.logD("DEBUG_DT", "THIS IS addOrderToBackstage-->ERR");
                    }
                });
    }

}
